<template>
  <div style="flex: 1">
    <div v-if="!isNoAction" class="ctl-box">
      <bs-add-icon @click.native="plusClick" class="bs-icon hover-effect" />
      <bs-remove-icon @click.native="removeClick" class="bs-icon hover-effect" />
      <bs-edit-icon @click.native="editClick" class="bs-icon hover-effect" />
      <bs-refresh-icon @click.native="refreshClick" class="bs-icon hover-effect" />
    </div>
    <div
      :class="[isNoAction ? 'no-ctl' : '', where === 'inner' ? 'inner' : '']"
      class="tree-box">
      <bs-tree
        ref="bsTree"
        :node-key="nodeKey"
        :highlight-current="highlight"
        :data="treeData"
        :default-props="treeProps"
        :default-checked-keys="defaultCheckedKeys"
        :default-expanded-keys="defaultExpandedKeys"
        :expand-on-click-node="expandOnClickNode"
        :show-checkbox="isCanCheck"
        :draggable="false"
        :filter-visible="false"
        :context-menu-visible="contextMenuVisible"
        :context-menu-data="contextMenuData"
        @node-click="nodeClick"
        @check="check"
        @handleRightSelect="handleRightSelect"
      ></bs-tree>
    </div>
    <media-menu-dialog
      v-if="!isNoAction"
      :visible.sync="dialogVisible"
      :form="form"
      :type="dialogType"
      :text="dialogText"
      @addClick="handleAdd"
      @updateClick="handleUpdate" />
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
import MediaMenuDialog from './MediaMenuDialog'
const {mapActions, mapGetters} = createNamespacedHelpers('media')

export default {
  props: {
    where: {
      type: String,
      default: ''
    },
    expandOnClickNode: {
      type: Boolean,
      default: true
    },
    contextMenuVisible: {
      type: Boolean,
      default: false
    },
    isNoAction: {
      type: Boolean,
      default: false
    },
    treeProps: {
      type: Object,
      default() {
        return {
          id: 'id',
          label: "name",
          children: 'children'
        }
      }
    },
    defaultCheckedKeys: {
      type: Array,
      default() {
        return []
      }
    },
    contextMenuData: {
      type: Array,
      default() {
        return []
      }
    },
    treeLoading: {
      type: Boolean,
      default: false
    },
    isCanCheck: {
      type: Boolean,
      default: false
    },
    highlight: {
      type: Boolean,
      default: true
    },
    apiObj: {
      type: Object,
      required: true
    },
    apiType: {
      type: String,
      required: true
    },
    nodeKey: {
      type: String,
      default: 'id'
    }
  },
  data() {
    return {
      form: {
        name: '',
        comment: ''
      },
      dialogVisible: false,
      dialogText: '',
      dialogType: '1', // 1 新增子目录 2 新增一级目录 3 编辑目录 4 删除目录 5 提示弹窗,
      defaultExpandedKeys: [],
    }
  },
  computed: {
    ...mapGetters(['menuTree']),
    treeData() {
      // 如果是媒体审核，则不需要显示下级用户
      if(this.apiType === '5') {
        return this.menuTree(this.apiType).filter(item => {
          if(item.id !== -1)
            return item
        })
      } else {
        return this.menuTree(this.apiType)
      }
    },
  },
  created() {
    console.log('------mediaMenuTree----created', this.where)
    this.fetchData()
    // 媒体审核不需要发送请求
    if(this.apiType !== '5') {
      this.fetchOtherData()
    }
    this.apiObj.bottomGet && this.initBottom()
  },
  components: {
    MediaMenuDialog
  },
  methods: {
    ...mapActions(['setMenuTree']),
    handleRightSelect(v) {
      console.log('----v', v)
    },
    nodeClick(data) {
      this.$emit('currentNodeData', data)
      if (data.id === 0 && data.disabled)  {
        this.$emit('myTop')
      }
    },
    check(data, arr) {
      this.$emit('check', data, arr)
    },
    plusClick() {
      console.log('新增目录')
      const currNodeData = this.$refs.bsTree.$refs.tree.getCurrentNode()
      if (!currNodeData) { // 添加一级目录
        this.form = {
          name: '',
          comment: '',
          parentId: 0,
          type: this.apiType
        }
        this.dialogType = '2'
        
        return 
      }
      if (currNodeData.id === -1 || currNodeData.id === -3 || currNodeData._isOther) {return this.$alert('提示', '此目录不可操作');} // 点了下级根目录或者自己的根目录 不允许操作

      
      this.form = {
        name: '',
        comment: '',
        parentId: currNodeData.id,
        parentName: currNodeData.name,
        type: this.apiType
      }
      if (currNodeData._isSub) {
        this.form.parentId = currNodeData.id ? currNodeData.id : 0
        this.form.ownerUserId = currNodeData.ownerUserId
        // 下级目录需要对参数处理
      }
      this.dialogType = '1'
      this.dialogVisible = true
    },
    async removeClick() {
      const currNodeData = this.$refs.bsTree.$refs.tree.getCurrentNode()
      if (!currNodeData) return
      if (currNodeData.id === -1 || currNodeData.id === -3 || currNodeData.id === 0 || currNodeData._isOther) {return this.$alert('提示', '此目录不可操作');} // 点了下级根目录或者自己的根目录 不允许操作

      
      const r1 = await this.$confirm('提示', '是否确定删除？')
      if (r1) {
        let params = {
          ...currNodeData,
          type: this.apiType
        }
        if (currNodeData._isSub) {
          if (!currNodeData.id) return this.$alert('提示', '此目录不可操作')
          params.id = currNodeData.id ? currNodeData.id : 0
          params.ownerUserId = currNodeData.ownerUserId
          // 下级目录需要对参数处理
        }
        currNodeData.type = this.apiType
        const r2 = await this.apiObj.del(params)
        console.log(r2)
        this.fetchData()
        this.apiObj.bottomGet && this.initBottom()
      } 
      

      
    },
    editClick() {
      const currNodeData = this.$refs.bsTree.$refs.tree.getCurrentNode()
      if (!currNodeData) return
      if (currNodeData.id === -1 || currNodeData.id === -3 || currNodeData.id === 0 || currNodeData._isOther) {return this.$alert('提示', '此目录不可操作');} // 点了下级根目录或者自己的根目录 不允许操作

      
      this.dialogType = '3'
      this.form = {
        id: currNodeData.id,
        oldName: currNodeData.name,
        name: '',
        comment: currNodeData.comment,
        type: this.apiType,
        ownerUserId: currNodeData.ownerUserId
      }
      if (currNodeData._isSub) {
        if (!currNodeData.id) return this.$alert('提示', '此目录不可操作')
        this.form.id = currNodeData.id ? currNodeData.id : 0
        this.form.ownerUserId = currNodeData.ownerUserId
        // 下级目录需要对参数处理
      }
      this.dialogVisible = true
      console.log('编辑目录')
    },
    refreshClick() {
      // this.$refs.bsTree.$refs.tree.setCurrentKey(null)
      // this.$emit('currentNodeData', null)
      console.log('刷新目录')
      this.fetchData()
      if(this.apiType !== '5') {
        this.fetchOtherData()
      }
      this.apiObj.bottomGet && this.initBottom()
    },
    async handleAdd (form, cb) {
      console.log('新增表单---', form)
      try {
        const res = await this.apiObj.add(form)
        cb(true)
        this.fetchData()
        this.apiObj.bottomGet && this.initBottom()
      } catch (error) {
        cb()
      }
    },
    async handleUpdate (form, cb) {
      console.log('更新表单---', form)
      try {
        const res = await this.apiObj.update(form)
         cb(true)
        this.fetchData()
        this.apiObj.bottomGet && this.initBottom()
      } catch (error) {
        cb()
      }
      this.apiObj.bottomGet && this.initBottom()
    },
    async fetchData() {
      try {
        const res = await this.apiObj.get({type: Number(this.apiType)})
        // 目录树数据存入vuex
        this.setMenuTree({
          treeData: res,
          type: this.apiType
        })
        if(this.apiType === '5') {
          this.$nextTick(() => {
            this.defaultExpandedKeys = [-3]
            this.$emit('currentNodeData', {id: -3})
            this.$refs.bsTree.$refs.tree.setCurrentKey(-3)
          })
        } else {
          this.$nextTick(() => {
            this.defaultExpandedKeys = [0]
            this.$refs.bsTree.$refs.tree.setCurrentKey(0)
            this.$emit('currentNodeData', {id: 0})
            if (this.apiType == 4) {
              // 对于发布计划默认不展开
              const refTree = this.$refs.bsTree.$refs.tree
              if (res && res.length > 0) {
                this.defaultExpandedKeys = [-1]
              } else {
                this.defaultExpandedKeys = []
              }
              // refTree.setCheckedNodes(res)
              // const checkedNodes = refTree.getCheckedNodes()
              // const checkedKeys = refTree.getCheckedKeys(true)
              // this.defaultExpandedKeys = checkedKeys
              // this.$emit('check', null, {checkedNodes, checkedKeys, halfCheckedNodes: [], halfCheckedKeys: []}) 
            }
          })
        }
      } catch (error) {
        console.log('mediaMenu---', error)
      }
    },
    // 获取其他资源
    async fetchOtherData() {
      if (!this.apiObj.getOtherMedia) return
      if(this.apiType !== '4') {
        const res = await this.apiObj.getOtherMedia({type: Number(this.apiType)})
        this.setMenuTree({
          otherMediaTreeData: res,
          type: this.apiType
        })
      }
    },
    async initBottom() {
      try {
        const res = await this.apiObj.bottomGet({type: Number(this.apiType)})
        // 目录树数据存入vuex
        this.setMenuTree({
          treeData: res,
          type: this.apiType,
          isSub: true
        })
      } catch (error) {
        console.log('initBottom', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';
.ctl-box {
  line-height: 1.15;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-bottom: 1px solid $bg-dc;
  padding: 12px 0 12px 0;
  margin: 0;
}
.tree-box {
  width: 248px;
  height: calc(100vh - 200px);
  overflow: auto;

  .tree {
    height: 100%;
    ::v-deep .el-tree {
      display: inline-block !important;
      min-width: 100%;
    }
  }

  &.no-ctl {
    height: calc(100vh - 150px);
    .tree {
      height: 100%;
      ::v-deep .el-tree {
        display: inline-block !important;
        min-width: 100%;
      }
    }
  }
  &.inner {
    width: 100%;
    height: auto;
    overflow: initial;

    .tree {
      height: auto;
    }
  }
}
// .bs-icon {
//   line-height: 36px;
// }
</style>